//
//  ProfitView.m
//  Bus
//
//  Created by wangjiajia on 13-7-8.
//  Copyright (c) 2013年 wangjiajia. All rights reserved.
//

#import "ProfitView.h"
#import "UIImage+UIImageExtras.h"
#import "WebServicesUtils.h"
#import "JsonParser.h"
#import "MBProgressHUD.h"
#import "Tools.h"
#import "ASIHTTPRequest.h"
#import "Profit.h"
@interface ProfitView (){
    BOOL isShow;
    MBProgressHUD * hud;
    NSArray* years;
    NSArray* months;
    
    NSInteger thisYear;//今年的年份
    NSInteger thisMonth;
    
    NSString * selectedYear;
    NSString * selectedMonth;
}

@end

@implementation ProfitView

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title=@"财务查询";
    
    UIImage *bgBarImg=[UIImage imageNamed:@"list_bg64"];
    [self.navigationController.navigationBar setBackgroundImage:bgBarImg forBarMetrics:UIBarMetricsDefault];
    //[self hideDatePick];
    
    UIImage *btnBg=[[UIImage imageNamed:@"news_bg@2x.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 15, 15, 15)];
    [self.search setBackgroundImage:btnBg forState:UIControlStateNormal];
    
    //NSLog(@"%@",[[NSDate date] description]);
    //这里构建年和月
    NSDate* dateNow=[NSDate date];
    NSCalendar* calendar=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents* comps=  [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit fromDate:dateNow];
    thisYear=comps.year;//今年的年份
    thisMonth=comps.month;
    NSMutableArray *showYears=[NSMutableArray array];
    //最近15年可选
    for (int i=14; i>=0; i--) {
        [showYears addObject:[NSString stringWithFormat:@"%d",thisYear-i]];
    }
    years=[NSArray arrayWithArray:showYears];
    
    NSMutableArray *showMonths=[NSMutableArray array];
    for (int i=1; i<=12; i++) {
        [showMonths addObject:[NSString stringWithFormat:@"%d",i]];
    }
    months=[NSArray arrayWithArray:showMonths];
    //NSLog(@"%.56f",DBL_EPSILON);// 浮点数最小精度
    if(IS_IPHONE_5){
        NSLog(@"IS_IPHONE_5");
        //针对IPhone5设计,不用调尺寸
    }else{
        NSLog(@"IS_IPHONE_4/4S");
        //修改UIWebView尺寸
        CGRect frame=self.webView.frame;
        frame.size.height-=88;
        self.webView.frame=frame;
    }
    
    
}
-(void)viewWillAppear:(BOOL)animated{
    //默认显示时，定位到当前年月
    [self.datePicker selectRow:14 inComponent:0 animated:YES ];
    [self.datePicker selectRow:thisMonth-1 inComponent:1 animated:YES ];
    
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setDatePicker:nil];
    [self setSearch:nil];
    [self setWebView:nil];
    [super viewDidUnload];
}

#pragma mark -自定义方法
-(void)popDatePick{
    //NSLog(@"pop");
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:@"show" context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.6];//动画时间长度，单位秒，浮点数
    CGRect dataPickerFrame=self.datePicker.frame;
    CGRect searchFrame=self.search.frame;
    //日期选择
    dataPickerFrame.origin.y+=216;//ios7:-152+216=64|ios6:-196+216=20;
    self.datePicker.frame =dataPickerFrame;
    //搜索按钮
    searchFrame.origin.y+=216;
    self.search.frame=searchFrame;
    [self.search setTitle:@"提交" forState:UIControlStateNormal];
    
    
    [UIView setAnimationDelegate:self];
    // 动画完毕后调用animationFinished
    [UIView setAnimationDidStopSelector:@selector(animationFinished)];
    [UIView commitAnimations];
    self.webView.hidden=YES;//日期出来，webView隐藏
}

-(void)hideDatePick{
    //NSLog(@"hide");
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:@"hide" context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.6];//动画时间长度，单位秒，浮点数
    
    CGRect dataPickerFrame=self.datePicker.frame;
    CGRect searchFrame=self.search.frame;
    
    dataPickerFrame.origin.y-=216;
    self.datePicker.frame = dataPickerFrame;
    
    searchFrame.origin.y-=216;
    self.search.frame=searchFrame;
    
    [self.search setTitle:@"检索" forState:UIControlStateNormal];
    //self.search.frame=CGRectMake(100,64,120,40);//不要写死了
    [UIView setAnimationDelegate:self];
    // 动画完毕后调用animationFinished
    [UIView setAnimationDidStopSelector:@selector(animationFinished)];
    [UIView commitAnimations];
    self.webView.hidden=NO;//日期隐藏，webView显示
}

- (IBAction)doSearch:(id)sender {
    //NSLog(@"doSearch");
    if(isShow){
        [self hideDatePick];
        isShow=NO;
        if(!hud)
        {
            hud=[[MBProgressHUD alloc] initWithView:self.view];
        }
        [Tools showHUD:@"正在获取数据..." andView:self.view andHUD:hud];
        
        //开始查询数据
        [WebServicesUtils
         getProfit:
         [[years objectAtIndex:[self.datePicker selectedRowInComponent:0]%15] intValue]
         andMonth:
         [[months objectAtIndex:[self.datePicker selectedRowInComponent:1]] intValue]
         withDelege:self];
    }else{
        [self popDatePick];
        isShow=YES;
    }
}


-(void)animationFinished{
    NSLog(@"动画结束!");
}

#pragma mark- UIPickerViewDataSource

// 返回显示的列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 2;
}

// 返回每一列中，显示的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component==0) {
        return years.count+15;//多一个循环
    }
    return months.count;
    
}

#pragma mark- UIPickerViewDelegate

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (component==0) {
        return [NSString stringWithFormat:@"%@年", [years objectAtIndex:row%15]];
    }
    return [NSString stringWithFormat:@"%@月", [months objectAtIndex:row%12]];
}

#pragma mark-网络请求结束
-(void)requestFinished:(ASIHTTPRequest *)request{
    if(hud){
        [hud hide:YES];
    }
    NSString * responseStr=[request responseString];
    //NSLog(@"响应字符串为%@",responseStr);
    NSMutableArray* profits=[JsonParser parseAsProfit:responseStr];
    //NSLog(@"解析数组为%@",profits);
    NSMutableString* htmlStr=[NSMutableString string];
    [htmlStr appendFormat:@"<html><body><table border='1' bordercolor=black cellspacing=0 cellpadding=0 width=\"100%%\"><tr><td colspan=4 style=\"text-align:center\"><label style='color:blue'>%@</label>年<label style='color:blue'>%@</label>月 利润表</td></tr> <tr bgcolor='#f5deb3'><th>项目</th><th>行数</th><th>本月数</th><th>本年累计数</th></tr>",[years objectAtIndex:[self.datePicker selectedRowInComponent:0]%15],[months objectAtIndex:[self.datePicker selectedRowInComponent:1]]];
    for(Profit* item in profits) {
        
        [htmlStr appendFormat:@"<tr><td>%@</td><td>%d</td><td>%@</td><td>%@</td></tr>",
         item.idesc,
         item.idNo,
         [item.SumP rangeOfString:@"-"].location==0?[NSString stringWithFormat:@"<font color='#c71585'>%@</font>",item.SumP]:[NSString stringWithFormat:@"<font color='black'>%@</font>",item.SumP],
         [item.SumY rangeOfString:@"-"].location==0?[NSString stringWithFormat:@"<font color='#c71585'>%@</font>",item.SumY]:[NSString stringWithFormat:@"<font color='black'>%@</font>",item.SumY]
         ];
        
    }
    
    [htmlStr appendString:@"</table></body></html>"];
    
    [self.webView loadHTMLString:[NSString stringWithString:htmlStr] baseURL:nil];
    NSLog(@"%@",NSStringFromCGRect(self.webView.frame));
}
#pragma mark-网络请求失败
-(void)requestFailed:(ASIHTTPRequest *)request{
    NSLog(@"处理请求失败%@",request.responseString);
    if(hud){
        [hud hide:YES];
    }
    [Tools toastNotification:@"请检查网络并确保财务服务器开启!" andView:self.view andLoading:NO andIsBottom:NO];
}
@end
